<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
				</div>
				<div class="flex-end-center-wrap">
					<!--<jk-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onReportBtn">导出</jk-button>-->
					<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" :clearable="true" placeholder="区域" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" placeholder="日期" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable />
					<jk-select v-model="searchParams.processCode" :clearable="true" value-key-name="code" :option-list="processList" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<!-- <jk-select v-model="searchParams.processCode" value-key-name="code" :option-list="processList" placeholder="工序" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select> -->
					<jk-search-input v-model="searchParams.code" placeholder="单据编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<!-- <span v-else-if="item.keyName === 'code'" :width="300">{{ scope.row.code }}</span> -->
						<span v-else-if="item.keyName === 'maxValue'">{{ `${scope.row.minValue}~${scope.row.maxValue}` }}</span>
						<div v-else-if="item.keyName === 'processList'">
							<div
								v-for="(processItem, processIndex) in scope.row.configItem || []"
								:key="processIndex"
							>{{ `${processIndex + 1}、${processItem.processName}: ${processItem.unitPrice}` }}</div>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="330">
					<template slot-scope="scope">
						<div class="flex-start-center">
							<jk-button icon="el-icon-printer" class="item-gap" size="mini" @click="onPrintBtn(scope.row)">打印</jk-button>
							<jk-operation-bar
								:scope="scope"
								api-prefix="production/change-spinning-plan"
								:api-item="apiItem"
								:permission-prefix="prefix"
								@on-detail="onDetailBtn"
								@on-edit="onEditBtn"
								@on-refresh="getListRequest"
							></jk-operation-bar>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			:request="getListRequest"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import {
        getChangePlan
    } from '@/api/production/planAlterSpinning';
    import { auditStateList } from '../../../utils/jk/status-option-list';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import { getChangePlanPage } from '@/api/production/planAlterSpinning';
    import { pageConfig, formatDate } from '/src/utils/jk/jk-tool';
    import { iotCollectDataCountPage } from '@/api/production/frontGroupYieldStatistics';

    export default {
        name: 'YarnCountPriceConfig',
        components: {
            saveDialog
        },
        mixins: [calHeight, getMenuColumn],
        data() {
            return {
                apiItem: {
                    'page': getChangePlan,
                    'details': getChangePlanPage
                },
                pageType: '',
                // 用户权限
                prefix: 'production:changeSpinningPlan',
                auditStateList: auditStateList,
                dataId: null,
                workshopList: [],
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                processList: [],
                createTime: '',
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    maxValue: null,
                    processCode: '',
                    auditState: null,
                    workshopId: '',
                    code: '',
                    processId: '',
                    belongDate: ''
                },
                shijian: []
            };
        },
        mounted() {
            this.getDependentData();
            // this.searchParams.belongDate = formatDate(Date.now());
            this.processList = this.$store.state.user.userProcess.processList;
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || 'XS');
            }
        },
        methods: {
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return getChangePlan(params).then(res => {
                        if (res.data.status === 200) {
                  import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = this.tableColumnList.map(x => x.title);
                    const filterVal = this.tableColumnList.map(x => x.keyName);
                    const list = JSON.parse(JSON.stringify(res.data.res)).map(item => {
                      return item;
                    });
                    const arr = ['auditState'];
                    list.forEach((obj) => {
                      Object.keys(obj).forEach((key) => {
                        arr.forEach(y => {
                          if (key === y) {
                            if (obj[key] === 1) {
                              obj[key] = '已审核';
                            } else {
                              obj[key] = '待审核';
                            }
                          }
                        });
                      });
                    });
                    const data = list.map(v => filterVal.map(j => {
                      return v[j];
                    }));
                    excel.export_json_to_excel({
                      header: tHeader,
                      data,
                      filename: `${this.$route.meta.title}`,
                      autoWidth: true,
                      bookType: 'xlsx'
                    });
                  });
                        }
                    });
                }).catch(() => {});
            },
            onPrintBtn(row) {
                this.$emit('on-visible-change', false);
                const routeUrl = this.$router.resolve({
                    name: 'printRenovate',
                    query: {
                        id: row.id
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            async getDependentData() {
                this.tableLoading = true;
                // this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.pageType = 'detail';
                this.dataId = e.id;
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.pageType = 'add';
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row.id;
                this.saveDialogState = true;
            }
        }
    };
</script>
